﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pb;
using System.Linq;
using UnityEngine.SceneManagement;


public class XTJFriendGame : Game
{

    EginUser user = EginUser.Instance;
    EginXTJ xtj = EginXTJ.Instance;
    private int uid;

    public List<XTJUser> xtjUsers;
    public GameObject Root;


    public GameObject exitBtn;
    public GameObject MoneyBtn;
    public GameObject SetBtn;
    public GameObject readyBtn;
    public GameObject bankBtn;
    //public GameObject QiangZhuang;
    public GameObject SetSaizi;//进行掷骰子操作

    #region 押注
    public GameObject ShunMen;
    public GameObject ShunJiao;
    public GameObject Tang;
    public GameObject Tianmen;
    public GameObject Daomen;
    public GameObject Daojiao;

    public int Direction;//下注方位
    //某个方位的总的筹码数显示框
    public List<UILabel> poolChipsCountLabels;
    //某个方位的自己下的筹码数显示框
    public List<UILabel> ownChipsCountLabels;
    //public List<long> poolChipsCountList;
    public List<long> ownChipsCountList;
    //等待好友显示框
    public GameObject waitFriend;
    public GameObject stopBet;

    public GameObject ChipPre;//下注的筹码预制体；
    //每局的牌
    public List<GameObject> roundCardsList;
    //所有的牌
    public List<UISprite> allCards;
    //牌原来的位置
    public List<Vector3> cardsOriginalPos;

    //发牌位置
    public Dictionary<int, GameObject> dealCardsPosDic = new Dictionary<int, GameObject>();
    //所发的牌
    public Dictionary<int, GameObject> dealCardsDic = new Dictionary<int, GameObject>();

    //所掷点数之和
    public int diceSum;
    public GameObject chipParent;//筹码父物体
    public GameObject RoomId;
    public List<UISprite> roomSprite;//房间号
    #endregion

    //音效
    public List<AudioClip> effectBgList;

    // Use this for initialization
    void Awake()
    {

        UIEventListener.Get(exitBtn).onClick = ButtonOnclick;
        UIEventListener.Get(MoneyBtn).onClick = ButtonOnclick;
        UIEventListener.Get(SetBtn).onClick = ButtonOnclick;
        UIEventListener.Get(readyBtn).onClick = ButtonOnclick;
        //UIEventListener.Get(QiangZhuang).onClick = ButtonOnclick;
        UIEventListener.Get(bankBtn).onClick = ButtonOnclick;
        UIEventListener.Get(ShunMen).onClick = ButtonOnclick;
        UIEventListener.Get(ShunJiao).onClick = ButtonOnclick;
        UIEventListener.Get(Tang).onClick = ButtonOnclick;
        UIEventListener.Get(Tianmen).onClick = ButtonOnclick;
        UIEventListener.Get(Daomen).onClick = ButtonOnclick;
        UIEventListener.Get(Daojiao).onClick = ButtonOnclick;

    }
    void Start()
    {        
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;

        uid = int.Parse(user.Uid);
        LoadUser();//加载玩家信息       
       
        xtj.currentChip = xtj.chipList[0];

                        
        string roomIdStr = xtj.roomId.ToString();
        for (int i = 0; i < roomIdStr.Length; i++)
        {
            string str = roomIdStr.ToString().Substring(i, 1);
            //roomIdStr = roomIdStr.Remove(0,1);
            roomSprite[i].spriteName = str;
        }
        RoomId.SetActive(true);
       

        if (xtj.isReady == true)
        {
            readyBtn.SetActive(true);
        }


    }
    void ButtonOnclick(GameObject Btn)
    {
        if (Btn.name == "ExitBtn")
        {
            PaiLeaveRoundRequest message = new PaiLeaveRoundRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiLeaveRoundRequest);
        }
        else if (Btn.name == "MoneyBtn")
        {
            GameObject AddMoney = NGUITools.AddChild(GameObject.Find("UI Root").gameObject, (GameObject)(Resources.Load(HallPrafabPath.AddMoney)));
            Add_MoneyModel addMoneyModel = AddMoney.GetComponent<Add_MoneyModel>();
            addMoneyModel.PayForGold.SetActive(true);
            addMoneyModel.PayForRoomCard.SetActive(false);
            addMoneyModel.TransferAccount.SetActive(false);
            addMoneyModel.GoldBtnBg.SetActive(true);
            addMoneyModel.RoomCardBtnBg.SetActive(false);
            addMoneyModel.TransfBtnBg.SetActive(false);
        }
        else if (Btn.name == "BankBtn")
        {
            GameObject bankPanel = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)Resources.Load(HallPrafabPath.Bank));
            BankModel bankModel = bankPanel.GetComponent<BankModel>();
            bankModel.sumLabel.text = "已存入:" + user.bankCoinCount + "万金币"; 
        }
        else if (Btn.name == "SetBtn")
        {
            NGUITools.AddChild(this.gameObject, (GameObject)(Resources.Load(GameXTJPrafabPath.XTJSetPanel)));
        }
        else if (Btn.name == "ReadyBtn")
        {
            //向服务器发送准备信息
            readyBtn.SetActive(false);
            PaiRoundReadyRequest message = new PaiRoundReadyRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiRoundReadyRequest);
        }
        else if (Btn.name == "QiangZhuangBtn")
        {
            //抢庄请求
            //QiangZhuang.SetActive(false);
            PaiGrabMasterRequest message = new PaiGrabMasterRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiGrabMasterRequest);
        }
        else if (Btn.name == "setSaizi")//掷骰子请求操作
        {
            SetSaizi.SetActive(false);
            PaiThrowDiceRequest message = new PaiThrowDiceRequest { };
            SocketManager socketManager = SocketManager.Instance;
            socketManager.SendProtobuf1(message, MsgId.PaiThrowDiceRequest);
        }
        else if (Btn.name == "ShunMen")
        {
            Direction = 1;
            ownChipsCountList[0] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }
        else if (Btn.name == "Tang")
        {
            Direction = 2;
            ownChipsCountList[1] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }
        else if (Btn.name == "Daomen")
        {
            Direction = 3;
            ownChipsCountList[2] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }
        else if (Btn.name == "Daojiao")
        {
            Direction = 4;
            ownChipsCountList[3] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }
        else if (Btn.name == "Tianmen")
        {
            Direction = 5;
            ownChipsCountList[4] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }
        else if (Btn.name == "ShunJiao")
        {
            Direction = 6;
            ownChipsCountList[5] += xtj.currentChip;
            PaiBetRequest(xtj.currentChip, Direction);
        }

    }
    void PaiBetRequest(long coin, int dir)
    {
        Debug.Log("下注请求,下注金币是：" + coin + ",下注方位是：" + dir);
        PaiBetRequest message = new PaiBetRequest { Coin = coin, Direction = dir };
        SocketManager socketManager = SocketManager.Instance;
        socketManager.SendProtobuf1(message, MsgId.PaiBetRequest);
    }

    public override void SocketReceiveMessage(byte[] data)
    {
        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(4).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);
        #region  加入房间
        //加入房间
        if (TempMsgID == MsgId.PaiEnterRoundBroadcast)
        {
            Pb.PaiEnterRoundBroadcast newpb = Pb.PaiEnterRoundBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("有玩家加入房间了");
            //if (newpb.Status == (int)STATUS.Success)
            {
                if (uid != newpb.Round.NewPlayer.Id)
                {
                    xtj.playersList.Add(newpb.Round.NewPlayer);
                    xtj.SortPlayer();
                    //判断是否显示等待好友加入显示框
                    if (xtj.playersList.Count == 1)
                    {
                        waitFriend.SetActive(true);
                    }
                    else
                    {
                        waitFriend.SetActive(false);
                    }
                    
                    //求得新加入的玩家在房间中的位置
                    int tempIndex = xtj.ReturnPlayerSeat(newpb.Round.NewPlayer.Id);
                    if (newpb.Round.NewPlayer.AvatarUrl != "")
                    {
                        WXAvatarManager._instance.GetWxAvatar(newpb.Round.NewPlayer.Id, xtjUsers[tempIndex].wxAvatar, newpb.Round.NewPlayer.AvatarUrl);
                        xtjUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
                    }
                    else
                    {
                        xtjUsers[tempIndex].avatar.spriteName = newpb.Round.NewPlayer.AvatarId.ToString();
                        xtjUsers[tempIndex].avatar.gameObject.SetActive(true);
                    }
                    xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(newpb.Round.NewPlayer.Coin);
                    xtjUsers[tempIndex].uid = newpb.Round.NewPlayer.Id;                                                                     
                }
                 
            }
        }
        #endregion 加入房间
        #region 自己离开房间响应
        //自己离开房间
        else if (TempMsgID == MsgId.PaiLeaveRoundResponse)
        {
            Pb.PaiLeaveRoundResponse newpb = Pb.PaiLeaveRoundResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {
                xtj.playersList.Clear();
                if (uid == xtj.bankerId)
                {
                    xtj.bankerId = 0;
                } 
                for (int i = 0; i < xtjUsers.Count; i++)
                {
                    xtjUsers[i].InitPlayer();                  
                }                
                SceneManager.LoadSceneAsync(ScenePath.Hall);
                
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion 自己离开房间响应
      
        #region 其他玩家离开房间
        //其他玩家离开房间
        else if (TempMsgID == MsgId.PaiLeaveRoundBroadcast)
        {
            Pb.PaiLeaveRoundBroadcast newpb = Pb.PaiLeaveRoundBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("有玩家离开房间了");
            //RemovePlayer(newpb.PlayerId);
            //求得离开玩家在房间中位置
            int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);                     
            xtjUsers[tempIndex].InitPlayer();
        }
        #endregion 其他玩家离开房间

        #region 玩家被踢出房间的广播
        else if (TempMsgID == MsgId.PaiKickOutRoundBroadcast)//被踢出去的玩家的广播
        {
            Pb.PaiKickOutRoundBroadcast newpb = Pb.PaiKickOutRoundBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log(user.Uid);
            //自己被踢出房间
            if (newpb.PlayerId.ToString() == user.Uid)
            {
                //user.zhunbei = false;
                xtj.playersList.Clear();
                xtjUsers[0].InitPlayer();
                SceneManager.LoadSceneAsync(ScenePath.Hall);
            }
            //其他人被踢出房间
            else
            {
               //得出其他人在房间中的位置
                int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
                xtjUsers[tempIndex].InitPlayer();
            }
        }
        #endregion 玩家被踢出房间的广播

        #region 通知玩家开始准备
        else if (TempMsgID == MsgId.PaiRoundReadyBroadcast)//通知玩家开始准备
        {
            Pb.PaiRoundReadyBroadcast newpb = Pb.PaiRoundReadyBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("接收到服务器发送的准备通知");
            if(uid == xtj.createrUid){
                xtjUsers[0].bankerIcon.SetActive(true);
                xtjUsers[0].QiangZhuangStatus.SetActive(true);
            }
            readyBtn.SetActive(true);
            //播放开始游戏音效
            SoundModel.PlaySound(effectBgList[4]);
        }
        #endregion 通知玩家开始准备

        #region  玩家准备响应
        else if (TempMsgID == MsgId.PaiRoundReadyResponse)
        {
            Pb.PaiRoundReadyResponse newpb = Pb.PaiRoundReadyResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("玩家准备响应");
            if (newpb.Status == (int)STATUS.Success)
            {
                readyBtn.SetActive(false);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion  玩家准备响应
        #region  玩家已经准备广播
        else if (TempMsgID == MsgId.PaiRoundReadyResultBroadcast)//通知玩家已经准备了
        {
            Pb.PaiRoundReadyResultBroadcast newpb = Pb.PaiRoundReadyResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //求得准备的玩家在房间中的位置
            int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
            xtjUsers[tempIndex].readyStatus.SetActive(true);

            if(uid == newpb.PlayerId){
                readyBtn.SetActive(false);
            }

            
        }
        #endregion  玩家已经准备广播

        #region  通知开始抢庄广播
        //else if (TempMsgID == MsgId.PaiGrabMasterBroadcast)//开始抢庄
        //{
        //    Pb.PaiGrabMasterBroadcast newpb = Pb.PaiGrabMasterBroadcast.Parser.ParseFrom(dataConcent);
        //    Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
        //    Debug.Log("开始抢庄");
        //    for (int i = 0; i < xtjUsers.Count; i++)
        //    {
        //        xtjUsers[i].readyStatus.SetActive(false);
        //    }
        //    readyBtn.SetActive(false);
        //    QiangZhuang.SetActive(true);

        //    xtj.grabMasterList = newpb.Players.ToList();
        //}
        #endregion  通知开始抢庄广播
        #region  开始抢庄响应
        //抢庄响应
        else if (TempMsgID == MsgId.PaiGrabMasterResponse)
        {
            Pb.PaiGrabMasterResponse newpb = Pb.PaiGrabMasterResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion  开始抢庄响应
        #region  抢庄结果广播
        else if (TempMsgID == MsgId.PaiGrabMasterResultBroadcast)//抢庄结果信息
        {
            Pb.PaiGrabMasterResultBroadcast newpb = Pb.PaiGrabMasterResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            for (int i = 0; i < xtjUsers.Count;i++ )
            {
                xtjUsers[i].bankerIcon.SetActive(false);
                xtjUsers[i].QiangZhuangStatus.SetActive(false);
            }

            //QiangZhuang.SetActive(false);
            if (uid == newpb.PlayerId)
            {
                xtj.isBanker = true;
            }
            //得到庄家在房间中的位置
            int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
            xtjUsers[tempIndex].bankerIcon.SetActive(true);
            xtjUsers[tempIndex].QiangZhuangStatus.SetActive(true);
            xtj.bankerId = newpb.PlayerId;
            //如果此时存在是否放弃坐庄或者上庄或者洗牌的按钮面板  销毁掉
            GameObject bankerDownPanel = GameObject.Find("UI Root/BankerDownPanel");
            GameObject bankerUpPanel = GameObject.Find("UI Root/BankerUpPanel");           
            if(bankerDownPanel != null){
                Destroy(bankerDownPanel);
            }
           
            if (bankerUpPanel != null)
            {
                Destroy(bankerUpPanel);
            }                    
        }
        #endregion  抢庄结果广播

        #region  开始下注广播
        else if (TempMsgID == MsgId.PaiBetBroadcast)//开始进行下注操作
        {
            Pb.PaiBetResultBroadcast newpb = Pb.PaiBetResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            //QiangZhuang.SetActive(false);
            Debug.Log("执行开始下注操作");
            for (int i = 0; i < xtjUsers.Count; i++)
            {
                xtjUsers[i].readyStatus.SetActive(false);
            }
            //播放开始下注音效
            SoundModel.PlaySound(effectBgList[0]);

            //加载下注时间
            GameObject betTime = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJ100PrefabPath.BetTime));
            betTime.transform.localPosition = new Vector3(-21, 277, 0);
            //加载筹码按钮
            if (xtj.isBanker == false)
            {
                GameObject chips = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.Chips));
                chips.transform.localPosition = new Vector3(22, -278, 0);
                xtj.currentChip = xtj.chipList[0];
            }

        }
        #endregion  开始下注广播

        #region  下注响应
        //下注响应
        else if (TempMsgID == MsgId.PaiBetResponse)
        {
            Pb.PaiBetResponse newpb = Pb.PaiBetResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion  下注响应

        #region  下注广播
        else if (TempMsgID == MsgId.PaiBetResultBroadcast)//有玩家进行下注操作
        {
            Pb.PaiBetResultBroadcast newpb = Pb.PaiBetResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //if (newpb.Status == (int)STATUS.Success)
            {
                //克隆筹码
                CloneChips(newpb.PlayerId, newpb.Direction, newpb.Coin);

                //显示各个位置的总筹码数
                foreach (KeyValuePair<int, long> keyValue in newpb.AllPlayerCoinMap)
                {
                    if (keyValue.Key == 1)
                    {
                        poolChipsCountLabels[0].text = newpb.AllPlayerCoinMap[1].ToString();
                    }
                    else if (keyValue.Key == 2)
                    {
                        poolChipsCountLabels[1].text = newpb.AllPlayerCoinMap[2].ToString();
                    }
                    else if (keyValue.Key == 3)
                    {
                        poolChipsCountLabels[2].text = newpb.AllPlayerCoinMap[3].ToString();
                    }
                    else if (keyValue.Key == 4)
                    {
                        poolChipsCountLabels[3].text = newpb.AllPlayerCoinMap[4].ToString();
                    }
                    else if (keyValue.Key == 5)
                    {
                        poolChipsCountLabels[4].text = newpb.AllPlayerCoinMap[5].ToString();
                    }
                    else if (keyValue.Key == 6)
                    {
                        poolChipsCountLabels[5].text = newpb.AllPlayerCoinMap[6].ToString();
                    }
                }
                //显示自己在各个位置所下的筹码数
                if (uid == newpb.PlayerId)
                {
                    foreach (KeyValuePair<int, long> keyValue in newpb.CurrentPlayerCoinMap)
                    {
                        if (keyValue.Key == 1)
                        {
                            ownChipsCountLabels[0].text = newpb.CurrentPlayerCoinMap[1].ToString();
                        }
                        else if (keyValue.Key == 2)
                        {
                            ownChipsCountLabels[1].text = newpb.CurrentPlayerCoinMap[2].ToString();
                        }
                        else if (keyValue.Key == 3)
                        {
                            ownChipsCountLabels[2].text = newpb.CurrentPlayerCoinMap[3].ToString();
                        }
                        else if (keyValue.Key == 4)
                        {
                            ownChipsCountLabels[3].text = newpb.CurrentPlayerCoinMap[4].ToString();
                        }
                        else if (keyValue.Key == 5)
                        {
                            ownChipsCountLabels[4].text = newpb.CurrentPlayerCoinMap[5].ToString();
                        }
                        else if (keyValue.Key == 6)
                        {
                            ownChipsCountLabels[5].text = newpb.CurrentPlayerCoinMap[6].ToString();
                        }
                    }
                }

                //更新玩家的金币数
                int tempIndex = xtj.ReturnPlayerSeat(newpb.PlayerId);
                xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(newpb.RestCoin);
            }
            //else
            //{
            //    user.logMsg = newpb.Msg;
            //    GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            //}

        }
        #endregion  下注广播

        #region  停止下注广播
        else if (TempMsgID == MsgId.PaiBetStopBroadcast)//停止押注
        {
            Pb.PaiBetStopBroadcast newpb = Pb.PaiBetStopBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            //显示停止下注
            stopBet.SetActive(true);
            //播放停止下注音效
            SoundModel.PlaySound(effectBgList[2]);

            StartCoroutine(HideStopBet());

            //销毁筹码面板
            GameObject chipPanel = GameObject.Find("UI Root/Chips");
            if (chipPanel != null)
            {
                Destroy(chipPanel);
            }
        }
        #endregion  停止下注广播

        #region  通知掷骰子广播
        else if (TempMsgID == MsgId.PaiThrowDiceBroadcast)//通知掷骰子
        {
            Pb.PaiThrowDiceBroadcast newpb = Pb.PaiThrowDiceBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("通知掷骰子");
            if (xtj.isBanker == true)
            {
                SetSaizi.SetActive(true);
            }
        }
        #endregion  通知掷骰子广播

        #region  掷骰子响应
        //掷骰子响应
        else if (TempMsgID == MsgId.PaiThrowDiceResponse)
        {
            Pb.PaiThrowDiceResponse newpb = Pb.PaiThrowDiceResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == (int)STATUS.Success)
            {

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion  掷骰子响应

        #region  掷骰子广播
        else if (TempMsgID == MsgId.PaiThrowDiceResultBroadcast)//開始擲骰子操作
        {
            Pb.PaiThrowDiceResultBroadcast newpb = Pb.PaiThrowDiceResultBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            SetSaizi.SetActive(false);
            GameObject dice = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.Shaizi));
            DiceModel diceModel = dice.GetComponent<DiceModel>();
            diceModel.diceAniObj.SetActive(true);
            diceSum = newpb.Points[0] + newpb.Points[1];
            //播放掷骰子音效
            SoundModel.PlaySound(effectBgList[5]);
            StartCoroutine(DiceAnimation(diceModel, newpb.Points.ToList()));

        }
        #endregion  掷骰子广播

        #region  发牌广播
        else if (TempMsgID == MsgId.PaiDealCardBroadcast)//进行发牌操作
        {
            Pb.PaiDealCardBroadcast newpb = Pb.PaiDealCardBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //销毁筛子
            GameObject dice = GameObject.Find("UI Root/Shaizi");
            if (dice != null)
            {
                Destroy(dice);
            }           
            //计算发牌顺序
            SortDealCards();
            //发牌
            Debug.Log("发牌：" + xtj.roundCardNum);
            StartCoroutine(DealCards(newpb,xtj.roundCardNum));
        }
        #endregion  发牌广播

        #region  通知玩家是否继续坐庄广播
        else if (TempMsgID == MsgId.PaiGiveUpMasterBroadcast)
        {
            Pb.PaiGiveUpMasterBroadcast newpb = Pb.PaiGiveUpMasterBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(uid == xtj.bankerId){
                NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.BankerDownPanel));
            }
            else
            {
                NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.BankerUpPanel));
            }
        }
        #endregion  通知玩家是否继续坐庄广播

        #region  玩家放弃坐庄响应
        else if (TempMsgID == MsgId.PaiGiveUpMasterResponse)
        {
            Pb.PaiGiveUpMasterResponse newpb = Pb.PaiGiveUpMasterResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(newpb.Status == (int)STATUS.Success){
                //放弃坐庄
                if(uid == xtj.bankerId){                  
                    //得到庄家在房间中的位置
                    int tempIndex = xtj.ReturnPlayerSeat(xtj.bankerId);
                    xtjUsers[tempIndex].bankerIcon.SetActive(false);
                    xtjUsers[tempIndex].QiangZhuangStatus.SetActive(false);                                        
                }                                             
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject msg = NGUITools.AddChild(Root, (GameObject)Resources.Load("LogMsg"));
            }
        }
        #endregion  玩家放弃坐庄响应

        #region  一局结束后的广播
        else if (TempMsgID == MsgId.PaiGameOverBroadcast)//一局结束后的广播
        {

        }
        #endregion  一局结束后的广播

        #region  好友场结束广播
        //好友场结束的结算面板
        else if (TempMsgID == MsgId.PaiRankBroadcast)
        {
            Pb.PaiRankBroadcast newpb = Pb.PaiRankBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            GameObject settlement = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.XTJSettlement));
            XTJSettlement xtjSettlement = settlement.GetComponent<XTJSettlement>();
            xtjSettlement.LoadInfo(newpb.Ranks.Ranks.ToList());
            xtj.roundCardNum = 0;
        }
        #endregion  好友场结束广播
      
        #region  询问庄家是否进行洗牌广播
        else if (TempMsgID == MsgId.PaiIsShuffleBroadcast)//询问玩家是否进行洗牌
        {
            Pb.PaiIsShuffleBroadcast newpb = Pb.PaiIsShuffleBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(uid == xtj.bankerId){
                NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.ShuffleCards));
            }
        }
        #endregion  询问庄家是否进行洗牌广播

        #region  洗牌响应
        else if (TempMsgID == MsgId.PaiShuffleResponse)//玩家进行洗牌请求后的回复
        {
            Pb.PaiShuffleResponse newpb = Pb.PaiShuffleResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("洗牌");
            //洗牌成功的操作
            GameObject shuffleCardsPanel = GameObject.Find("UI Root/ShuffleCardsPanel");
            if (shuffleCardsPanel != null)
            {
                Destroy(shuffleCardsPanel);
            }
    
            if (newpb.Status == 1)//1代表成功
            {
                           
            }
            else
            {
                user.logMsg = newpb.Msg;
                NGUITools.AddChild(this.gameObject, (GameObject)(Resources.Load("LogMsg")));
            }
        }
        #endregion  洗牌响应

        #region  通知玩家洗牌广播
        else if (TempMsgID == MsgId.PaiShuffleBroadcast)//通知玩家洗牌了，播放洗牌动画
        {
            Pb.PaiShuffleBroadcast newpb = Pb.PaiShuffleBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);

            xtj.roundCardNum = 0;
            for (int i = 0; i < roundCardsList.Count;i++ )
            {
                RoundCards roundCards = roundCardsList[i].GetComponent<RoundCards>();
                for (int j = 0; j < roundCards.cardsList.Count;j++ )
                {
                    Cards cards = roundCards.cardsList[j].GetComponent<Cards>();
                    for (int k = 0; k < cards.cardsSprites.Count;k++ )
                    {
                        cards.cardsSprites[k].spriteName = "0";
                        cards.cardsTypeLabel.gameObject.SetActive(false);
                    }
                }
            }

        }
        #endregion  通知玩家洗牌广播

         //网络异常
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("NetWorkAbnormal")));
        }    

    }

    /// <summary>
    /// 加载玩家信息
    /// </summary>
    void LoadUser()
    {
        Debug.Log("进入房间，加载玩家" + xtj.playersList.Count);
        xtj.SortPlayer();
        for (int i = 0; i < xtj.playersList.Count; i++)
        {           
            //求得房间中的玩家在房间中的位置
            int tempIndex = xtj.ReturnPlayerSeat(xtj.playersList[i].Id);
            Debug.Log(xtj.playersList[i].Id + "   " + tempIndex);
            if (xtj.playersList[i].AvatarUrl != "")
            {               
                WXAvatarManager._instance.GetWxAvatar(xtj.playersList[i].Id, xtjUsers[tempIndex].wxAvatar, xtj.playersList[i].AvatarUrl);
                xtjUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
            }
            else
            {
                Debug.Log("头像id = " + xtj.playersList[i].AvatarId);
                xtjUsers[tempIndex].avatar.spriteName = xtj.playersList[i].AvatarId.ToString();
                xtjUsers[tempIndex].avatar.gameObject.SetActive(true);
            }
            xtjUsers[tempIndex].goldLabel.text = user.ReturnMoneyForLong(xtj.playersList[i].Coin);
            xtjUsers[tempIndex].uid = int.Parse(user.Uid);

        } 

        //显示庄家信息      
        //求得庄家在房间中的位置
        if(xtj.bankerId != 0){
            int tempIndex1 = xtj.ReturnPlayerSeat(xtj.bankerId);
            xtjUsers[tempIndex1].QiangZhuangStatus.SetActive(true);
            xtjUsers[tempIndex1].bankerIcon.SetActive(true);
        }
        
        //显示发牌的历史记录
        for (int i = 0; i < xtj.cardHistory.Count;i++ )
        {
            allCards[i].spriteName = xtj.cardHistory[i].Id.ToString();
        }

        //显示各个方位的总筹码数
        for (int i = 0; i < xtj.newpb.AllChips.Count; i++)
        {
            KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.AllChips.ElementAt(i);
            long sum = 0;
            for (int j = 0; j < keyValue.Value.Value.Count; j++)
            {
                ReconnectCloneChip(keyValue.Value.Value.Count, keyValue.Value.Value[j], keyValue.Key);
                sum += keyValue.Value.Value[j];
            }
            poolChipsCountLabels[keyValue.Key - 1].text = sum.ToString();
        }
        //显示自己在各个方位下的筹码数
        for (int i = 0; i < xtj.newpb.SelfChips.Count; i++)
        {
            KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.SelfChips.ElementAt(i);
            long ownSum = 0;
            for (int j = 0; j < keyValue.Value.Value.Count; j++)
            {
                ownSum += keyValue.Value.Value[j];
            }
            ownChipsCountLabels[keyValue.Key - 1].text = ownSum.ToString();
        }

        //显示当前发的牌
        if(xtj.newpb.CardMap.Count > 0){
            RoundCards roundCards = roundCardsList[xtj.roundCardNum].GetComponent<RoundCards>();
            cardsOriginalPos.Clear();
            for (int i = 0; i < xtj.newpb.CardMap.Count;i++ )
            {
                cardsOriginalPos.Add(roundCards.cardsList[i].transform.localPosition);
                Debug.Log("roundCards.cardsList[i].transform.localPosition = " + roundCards.cardsList[i].transform.localPosition);
                KeyValuePair<int,PaiCardGroup> keyValue = xtj.newpb.CardMap.ElementAt(i);
                if (keyValue.Key == 1)
                {
                    roundCards.cardsList[i].transform.localPosition = ShunMen.transform.localPosition;
                }
                else if (keyValue.Key == 2)
                {
                    roundCards.cardsList[i].transform.localPosition = Tang.transform.localPosition;
                }
                else if (keyValue.Key == 3)
                {
                    roundCards.cardsList[i].transform.localPosition = Daomen.transform.localPosition;
                }
                else if (keyValue.Key == 5)
                {
                    roundCards.cardsList[i].transform.localPosition = Tianmen.transform.localPosition;
                }
                dealCardsDic.Add(keyValue.Key, roundCards.cardsList[i]);
                roundCards.cardsList[i].GetComponent<Cards>().destination = roundCards.cardsList[i].transform.localPosition;
                roundCards.cardsList[i].GetComponent<Cards>().ShowCards(keyValue.Value.Cards.ToList(),keyValue.Value.Form);                
            }
        }

        //显示一局结束之后的分数和金币数
        if(xtj.newpb.CoinMap.Count > 0){
            GameObject gameOverPanel = NGUITools.AddChild(Root,(GameObject)Resources.Load(GameXTJPrafabPath.GameOver));
            GameOver gameOver = gameOverPanel.GetComponent<GameOver>();
            for (int i = 0; i < xtj.newpb.CoinMap.Count;i++ )
            {
                KeyValuePair<int, PaiInt64Array> keyValue = xtj.newpb.CoinMap.ElementAt(i);
                //求得玩家在房间中对应的位置
                int tempIndex = xtj.ReturnPlayerSeat(keyValue.Key);
                Debug.Log(keyValue.Key + "   " + tempIndex);
                //显示输赢的金币数
                gameOver.ShowScore(keyValue.Value.Value[0], gameOver.ScoreSprites[tempIndex], gameOver.ScoreFathers[tempIndex], gameOver.JiaJians[tempIndex]);
                //显示剩余的金币数
                xtjUsers[tempIndex].goldLabel.text = EginUser.Instance.ReturnMoneyForLong(keyValue.Value.Value[1]);
                    
                if (int.Parse(EginUser.Instance.Uid) == keyValue.Key)
                {
                    EginUser.Instance.coinCount = keyValue.Value.Value[1].ToString();
                }
            }
        }


    }
   
    /// <summary>
    /// 骰子动画
    /// </summary>
    /// <param name="diceModel"></param>
    /// <param name="points"></param>
    /// <returns></returns>
    IEnumerator DiceAnimation(DiceModel diceModel, List<int> points)
    {
        yield return new WaitForSeconds(1.5f);
        diceModel.diceAniObj.SetActive(false);
        diceModel.dice1.spriteName = "shaizi" + points[0].ToString();
        diceModel.dice2.spriteName = "shaizi" + points[1].ToString();
        diceModel.dice1.gameObject.SetActive(true);
        diceModel.dice2.gameObject.SetActive(true);
    }

    /// <summary>
    /// 克隆筹码
    /// </summary>
    public void CloneChips(int id, int direction, long chipCoin)
    {
        Vector3 tempPos = new Vector3();
        GameObject chip = Instantiate(ChipPre);
        chip.transform.SetParent(chipParent.transform);
        chip.transform.localScale = new Vector3(0.5f, 0.5f, 1);
        Debug.Log("筹码图片名称：" + xtj.level + "_" + (chipCoin / 10000));
        chip.GetComponent<UISprite>().spriteName = xtj.level + "_" + (chipCoin / 10000);
        //确定是谁下的注
        //得到下注人在房间中的位置
        int tempIndex = xtj.ReturnPlayerSeat(id);
        chip.transform.localPosition = xtjUsers[tempIndex].transform.localPosition;

        //确定移动的终点
        if (direction == 1)
        {
            tempPos = new Vector3(Random.Range(-7, 102), Random.Range(-8, 60), 0);
        }
        else if (direction == 2)
        {
            tempPos = new Vector3(Random.Range(147, 285), Random.Range(23, 60), 0);
        }
        else if (direction == 3)
        {
            tempPos = new Vector3(Random.Range(330, 437), Random.Range(-38, 60), 0);
        }
        else if (direction == 4)
        {
            tempPos = new Vector3(Random.Range(326, 430), Random.Range(-156, -110), 0);
        }
        else if (direction == 5)
        {
            tempPos = new Vector3(Random.Range(147, 285), Random.Range(-156, -47), 0);
        }
        else if (direction == 6)
        {
            tempPos = new Vector3(Random.Range(0, 101), Random.Range(-156, -110), 0);
        }
        ChipsMove chipsMove = chip.GetComponent<ChipsMove>();
        chipsMove.destination = tempPos;
        chip.SetActive(true);
        //播放加注音效
        SoundModel.PlaySound(effectBgList[1]);
    }

    /// <summary>
    /// 确定发牌的顺序
    /// </summary>
    /// <returns></returns>
    public void SortDealCards()
    {
        Debug.Log("dealCardsPosDic = " + dealCardsPosDic.Count);
        int num = diceSum % 4;
        if (num == 0)
        {
            dealCardsPosDic.Add(2, Tang);
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
        }
        else if (num == 1)
        {
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
        }
        else if (num == 2)
        {
            dealCardsPosDic.Add(5, Tianmen);
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
            dealCardsPosDic.Add(1, ShunMen);
        }
        else if (num == 3)
        {
            dealCardsPosDic.Add(3, Daomen);
            dealCardsPosDic.Add(2, Tang);
            dealCardsPosDic.Add(1, ShunMen);
            dealCardsPosDic.Add(5, Tianmen);
        }
    }

    /// <summary>
    /// 发牌
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>
    IEnumerator DealCards(PaiDealCardBroadcast newpb,int round)
    {
        dealCardsDic.Clear();
        cardsOriginalPos.Clear();
        //播放发牌音效
        SoundModel.PlaySound(effectBgList[3]);
        //按顺序移动牌
        RoundCards roundCards = roundCardsList[round].GetComponent<RoundCards>();
        for(int i = 0;i < roundCards.cardsList.Count;i++){
            //先记录原来牌的位置            
            cardsOriginalPos.Add(roundCards.cardsList[i].transform.localPosition);

            Cards cards = roundCards.cardsList[i].GetComponent<Cards>();
            KeyValuePair<int, GameObject> element = dealCardsPosDic.ElementAt(i);
            cards.destination = element.Value.transform.localPosition;
            cards.enabled = true;
            dealCardsDic.Add(element.Key, roundCards.cardsList[i]);
            yield return new WaitForSeconds(0.5f);
        }

        yield return new WaitForSeconds(2f);
        StartCoroutine(ShowCards(newpb));
    }

    /// <summary>
    /// 展示牌
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>
    IEnumerator ShowCards(PaiDealCardBroadcast newpb)
    {      
        for (int i = 0; i < dealCardsPosDic.Count; i++)
        {
            KeyValuePair<int, GameObject> element = dealCardsDic.ElementAt(i);
            foreach (KeyValuePair<int, PaiCardGroup> keyValue in newpb.CardMap)
            {
                if (element.Key == keyValue.Key)
                {
                    Cards cards = element.Value.GetComponent<Cards>();
                    cards.ShowCards(newpb.CardMap[keyValue.Key].Cards.ToList(), newpb.CardMap[keyValue.Key].Form);
                }
            }
            yield return new WaitForSeconds(0.5f);
        }

        //加载游戏结束面板
        GameObject gameOverPanel = NGUITools.AddChild(Root, (GameObject)Resources.Load(GameXTJPrafabPath.GameOver));
        GameOver gameOver = gameOverPanel.GetComponent<GameOver>();
        gameOver.newpb = newpb;
        Debug.Log("xtj.roundCardNum = " + xtj.roundCardNum);
        xtj.roundCardNum++;
        
    }

    /// <summary>
    /// 牌返回原来的位置
    /// </summary>
    public void BackOriginal()
    {
        StartCoroutine(BackReturn());
    }

    IEnumerator BackReturn()
    {
        Debug.Log("cardsOriginalPos.Count = " + cardsOriginalPos.Count);
        Debug.Log("dealCardsDic.Count = " + dealCardsDic.Count);
        for (int i = 0; i < cardsOriginalPos.Count; i++)
        {
            KeyValuePair<int, GameObject> keyValue = dealCardsDic.ElementAt(i);
            keyValue.Value.GetComponent<Cards>().enabled = true;
            keyValue.Value.GetComponent<Cards>().destination = cardsOriginalPos[i];
            keyValue.Value.GetComponent<Cards>().cardsTypeLabel.gameObject.SetActive(false);
            yield return new WaitForSeconds(0.5f);
        }

        dealCardsDic.Clear();
        dealCardsPosDic.Clear();
    }

    /// <summary>
    /// 恢复初始状态
    /// </summary>
    public void RecoverInit()
    {
        //玩家恢复
        for (int i = 0; i < xtjUsers.Count; i++)
        {
            xtjUsers[i].readyStatus.SetActive(false);
            //xtjUsers[i].QiangZhuangStatus.SetActive(false);
            //xtjUsers[i].bankerIcon.SetActive(false);
        }

        //筹码销毁
        for (int i = 0; i < chipParent.transform.childCount; i++)
        {
            Destroy(chipParent.transform.GetChild(i).gameObject);
        }
        //筹码数置空
        for (int i = 0; i < poolChipsCountLabels.Count; i++)
        {
            poolChipsCountLabels[i].text = "";
            ownChipsCountLabels[i].text = "";
            ownChipsCountList[i] = 0;
        }

        xtj.isReady = false;       
        
    }

    /// <summary>
    /// 隐藏停止下注显示框
    /// </summary>
    /// <returns></returns>
    IEnumerator HideStopBet()
    {
        yield return new WaitForSeconds(1f);
        stopBet.SetActive(false);
    }


    /// <summary>
    /// 重连克隆筹码
    /// </summary>
    void ReconnectCloneChip(int count, long spriteNameId, int direction)
    {
        Vector3 tempPos = new Vector3();
        //for (int i = 0; i < count; i++)
        {
            GameObject chip = Instantiate(ChipPre);
            chip.transform.parent = chipParent.transform;            
            Debug.Log("筹码图片名称：" + xtj.level + "_" + (spriteNameId / 10000));
            chip.GetComponent<UISprite>().spriteName = xtj.level + "_" + (spriteNameId / 10000);
            chip.GetComponent<UISprite>().MakePixelPerfect();
            chip.transform.localScale = new Vector3(0.5f, 0.5f, 1);

            //确定移动的终点
            if (direction == 1)
            {
                tempPos = new Vector3(Random.Range(-7, 102), Random.Range(-8, 60), 0);
            }
            else if (direction == 2)
            {
                tempPos = new Vector3(Random.Range(147, 285), Random.Range(23, 60), 0);
            }
            else if (direction == 3)
            {
                tempPos = new Vector3(Random.Range(330, 437), Random.Range(-38, 60), 0);
            }
            else if (direction == 4)
            {
                tempPos = new Vector3(Random.Range(326, 430), Random.Range(-156, -110), 0);
            }
            else if (direction == 5)
            {
                tempPos = new Vector3(Random.Range(147, 285), Random.Range(-156, -47), 0);
            }
            else if (direction == 6)
            {
                tempPos = new Vector3(Random.Range(0, 101), Random.Range(-156, -110), 0);
            }
            ChipsMove chipsMove = chip.GetComponent<ChipsMove>();
            chip.transform.localPosition = tempPos;
            chipsMove.destination = tempPos;
            chip.SetActive(true);
        }
    }
}